﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace SocketServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private static byte[] result = new byte[1024];  //接受数据缓存
        private static int myProt = 8885;   //端口
        static Socket serverSocket;
        int file_name = 0;
        private static byte[] senddata = new byte[1024];
        private void Form1_Load(object sender, EventArgs e)
        {   //开启消息收发监听线程
            Thread SocketMessage = new Thread(ListenMessage);
            SocketMessage.IsBackground = true;
            SocketMessage.Start();
            //开启文件上传监听线程
            Thread SocketFile = new Thread(ListenFile);
            SocketFile.IsBackground = true;
            SocketFile.Start();
            
        }
        private void ListenMessage()
        {   //服务器IP地址
            IPAddress ip = IPAddress.Parse("192.168.0.86");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址：端口
            serverSocket.Listen(10);    //设定最多10个排队连接请求
            label1.Text = "启动监听成功:" + serverSocket.LocalEndPoint.ToString();
            //通过Clientsoket发送数据
            Thread myThread = new Thread(ListenClientConnect);
            myThread.Start();
        }

        // 监听客户端连接
        private void ListenClientConnect()
        {   
            while (true)
            {
                
                Socket clientSocket = serverSocket.Accept();
                //Socket发送数据
                //clientSocket.Send(Encoding.ASCII.GetBytes("file-F:\\TDDownload\\ppt2699.jpg"));
                //clientSocket.Send(Encoding.ASCII.GetBytes("cmd-ipconfig"));
                clientSocket.Send(senddata);
                //开启接受消息进程
                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientSocket);
                

            }
        }


        // 接收消息
        private void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据
                    
                    int receiveNumber = myClientSocket.Receive(result);
                    label1.Text = myClientSocket.RemoteEndPoint.ToString() + ":" + Encoding.UTF8.GetString(result, 0, receiveNumber);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }



        //接受客服端传回的文件
        private void ListenFile()
        {
            Thread TempThread = new Thread(new ThreadStart(this.StartReceive));
            TempThread.Start();

        }


        private void StartReceive()
        {   
            //初始化Socket
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.0.86"), 7000);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(ipep);
            server.Listen(10);
            while(true)
            {
            Socket client = server.Accept();
            
            file_name += 1;
            string fileaddr = file_name.ToString() + ".jpg";  
            FileStream MyFileStream = new FileStream(fileaddr, FileMode.Create, FileAccess.Write);  
        while(true)  
       {  
           byte[] data = TransferFiles.ReceiveVarData(client);  
           if(data.Length == 0)  
            {  
                break;  
            }  
            else  
            {  
               // SendedCount++;  
                MyFileStream.Write(data, 0, data.Length);  
           }  
        }  
  
        MyFileStream.Close();  
  
        client.Close();  
            }

        }

        private void FormClose(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(1);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            senddata = Encoding.ASCII.GetBytes(textBox1.Text);
        }
    }
}
